package com.zbkj.service.util;

import com.zbkj.common.constants.Constants;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@Component
public class FileUtil {

    @Value("${zb.reportfile}")
    private String saveFilePath;

    /**
     * 保存上传的文件到指定目录
     * @param file 上传的文件
     * @return 返回相对路径（相对于上传目录）
     * @throws IOException
     */
    public String saveFile(MultipartFile file) throws IOException {
        // 确保上传目录存在
        File dir = new File(saveFilePath + Constants.PICTURE_LOCAL_DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 生成唯一文件名
        String originalFilename = StringUtils.cleanPath(file.getOriginalFilename());
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String uniqueFilename = UUID.randomUUID() + fileExtension;

        // 创建目标文件路径
        Path targetLocation = Paths.get(saveFilePath + Constants.PICTURE_LOCAL_DIR).resolve(uniqueFilename);

        // 保存文件
        Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

        return uniqueFilename;
    }
}
